package edu.stanford.prpl.dynUI.templates;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class UIModelData
{   
    public Map<String,String> attributesStore = new HashMap<String,String>();
    public ArrayList<UIModelData> childUIElementsData = new ArrayList<UIModelData>();
    public UITemplate uiTemplate = null;
    public Object uiObject = null;
    
    public UIModelData()
    { }
    
    public static String fillStrWithAttr(UIModelData attrInfo, String strTemplate)
    {
        String[] result = strTemplate.split("\\{|\\}");
        String remainderStr = strTemplate;
        String testStrTransformed = "";
        String attrVal = null;
        
        for (int i = 0; i < result.length; i++)
        {
            if (result[i].length() <= 0)
               continue;
            
            String checkMatch = "{"+result[i]+"}";
            int indexLoc = remainderStr.indexOf(checkMatch);
            if (indexLoc < 0)
                continue;
            
            attrVal = UIModelData.resolveAttrValue(attrInfo, result[i]);
            if (attrVal != null)
            {
                if (indexLoc > 0)
                   testStrTransformed += remainderStr.substring(0, indexLoc);
                testStrTransformed += attrVal;
                remainderStr = remainderStr.substring(indexLoc+checkMatch.length());
            }
        }
        
        testStrTransformed += remainderStr;
        return testStrTransformed;
    }
    
    
    private static String resolveAttrValue(UIModelData attrInfo, String attrRef)
    {
        // Make sure it is of the form "this.validattrname"
        String[] result = attrRef.split("\\.");
        Map<String,String> attrStore = attrInfo.attributesStore;

        if (result.length <= 1)
            return null;

        // Determine the attrStore
        // Valid: "this.parent.parent.validattrname"
        if (!result[0].equals("this"))
           return null;
        
        /*
        for (int i = 1; i < result.length-1; i++)
        {
            if (!result[i].equals("parent"))
               return null;
            currentUIModelData = UIModelData.parent;
            attrStore = currentUIModelData.attrStore;               
        }
        */
        
        return (String)attrStore.get(result[1]);
    }    
    
    
}
